package org.zyx.item.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.zyx.item.entity.Category;
import org.zyx.item.service.CategoryService;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryHandler {

    @Resource
    private CategoryService categoryService;

    /**
     * 通过parentId获取分类列表
     * @param pid
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<Category>> findCategoryByPid(
            @RequestParam(value = "pid",defaultValue = "0") Long pid){
        try {
            if(pid == null || pid < 0){
                //返回错误信息:400 请求参数不合法
//                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
                //简写:
//                return new RequestEntity<>(HttpStatus.BAD_REQUEST);
                return ResponseEntity.badRequest().build();
            }
            List<Category> categoryList = this.categoryService.findCategoryByPid(pid);
            //使用集合工具类判断集合是否为空
            if(CollectionUtils.isEmpty(categoryList)){
                //404:资源服务器未找到
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            //200:查询成功则将list返回
            return ResponseEntity.ok(categoryList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //ctrl+alt+t:快速捕获异常
        //500 :服务器内部错误,可以不处理,出错自动报500
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    /**
     * 添加分类
     * @param category  需要添加注解,接收前端传递的json对象
     * @return
     */
    @PostMapping("/addCategory")
    public ResponseEntity addCategory(@RequestBody Category category){
        long id = categoryService.addCategory(category);
        return ResponseEntity.ok(id);
    }

    /**
     * 根据Id删除分类
     * @param id
     * @return
     */
    @DeleteMapping("/deleteCategoryById/{id}")
    public ResponseEntity deleteCategoryById(@PathVariable("id") Long id){
        if(categoryService.deleteCategoryById(id) == 0){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok().build();
    }


    /**
     * 根据商品分类id查询名称
     * @param ids 要查询的分类id集合
     * @return 多个名称的集合
     */
    @GetMapping("/names")
    public ResponseEntity<List<String>> queryNameByIds(@RequestParam("ids") List<Long> ids){
        List<String > list = this.categoryService.findByIds(ids);
        if (list == null || list.size() < 1) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(list);
    }






}
